package test.yzx.pproject.act1;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ScrollView;

import test.yzx.pproject.R;
import test.yzx.pproject.ViewAnimatorUtil;

public class Anim4Activity extends AppCompatActivity {

    private ScrollView sv;
    private View view;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.anim4);
        sv = (ScrollView) findViewById(R.id.sv);
        view = findViewById(R.id.view);

        getWindow().getDecorView().post(new Runnable() {
            public void run() {

                final int viewMaxDistanceX = getResources().getDisplayMetrics().widthPixels - view.getWidth();
                final int viewMaxDistanceY = (int) (100 * getResources().getDisplayMetrics().density);
                final int contractMaxDistance = (int) (100 * getResources().getDisplayMetrics().density);

                sv.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                    public void onScrollChanged() {
                        int contractNowDistance = sv.getScrollY();
                        float viewNowDistanceX = ViewAnimatorUtil.calculateRange(contractMaxDistance, contractNowDistance, viewMaxDistanceX);
                        float viewNowDistanceY = ViewAnimatorUtil.calculateRange(contractMaxDistance, contractNowDistance, viewMaxDistanceY);
                        view.setTranslationX(viewNowDistanceX);
                        view.setTranslationY(viewNowDistanceY);
                    }
                });
            }
        });

    }

}
